import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * 表格的中间类，与不同格式的数据进行转换
 * Created by LuoTao on 2016/10/25.
 * LemonTech Copyright reserved.
 */
public class Table {
    private static Logger logger = LogManager.getLogger(Table.class);
    private String[] header;
    private List<String[]> tableData = new LinkedList<>();
    private Iterator cursor = null;

    /**
     * 表格的转置
     *
     * @return 新的表格
     */
    public Table Transpose(String tableName) {
        logger.info(tableName + "正在进行转置");
        int colLength = tableData.size() + 1;
        String[] newHeader = new String[colLength];
        newHeader[0] = header[0];
        for (int i = 0; i < tableData.size(); ++i) {
            newHeader[i + 1] = tableData.get(i)[0];
        }
        Table tTable = new Table();
        tTable.initHeader(newHeader);
        for (int i = 1; i < header.length; ++i) {
            String[] newRowData = new String[colLength];
            newRowData[0] = header[i];
            for (int j = 0; j < tableData.size(); ++j) {
                newRowData[j + 1] = tableData.get(j)[i];
            }
            tTable.insertRow(newRowData);
        }
        return tTable;
    }

    /**
     * 将整个表格的数据根据配置表进行改名字。方便查看（hive）
     *
     * @param translate
     */
    public void Translate(Map<String, String> translate) {
        for (int i = 0; i < header.length; i++) {
            if (translate.containsKey(header[i])) {
                header[i] = translate.get(header[i]);
            }
        }
        for (String[] row_data : tableData) {
            for (int i = 0; i < row_data.length; i++) {
                if (translate.containsKey(row_data[i])) {
                    row_data[i] = translate.get(row_data[i]);
                }
            }
        }
    }

    public int getColumnNums() {
        if (header == null) {
            logger.error("当前table未被初始化");
            return 0;
        }
        return header.length;
    }

    public String[] getHeader() {
        return header;
    }

    /**
     * 重置迭代器
     */
    public void reset() {
        cursor = tableData.listIterator();
    }

    /**
     * 获取下一条数据
     *
     * @return 字符串数组
     */
    public String[] getNext() {
        if (cursor == null) {
            cursor = tableData.listIterator();
        }
        if (!cursor.hasNext()) {
            return null;
        }
        return (String[]) cursor.next();
    }

    public void initHeader(String[] header){
        this.header = header;
    }

    public void insertRow(String[] rowData){
        tableData.add(rowData);
    }
}
